<template>
  <div id="detail">
    <detail-nav-bar class="detail-nav" @titleClick="titleClick" ref="nav" />

    <scroll
      class="content"
      ref="scroll"
      :probe-type="3"
      @scroll="contentSrcoll"
    >
      <detail-swiper :top-images="topImages" />
      <detail-base-info :goods="goods" />
      <detail-shop-info :shop="shop" />
      <detail-goods-info :detail-info="detailInfo" @imageLoad="imageLoad" />
      <detail-param-info
        ref="param"
        :paramInfo="goodsParam"
      ></detail-param-info>
      <detail-comment-info
        ref="comment"
        :commentInfo="commentInfo"
      ></detail-comment-info>
      <goods-list ref="recommend" :goods="recommends"></goods-list>
    </scroll>
    <!-- 监听组件根元素的原生事件 -->
    <back-top v-show="isShowBackTop" @click.native="backClick" />
    <detail-bottom-bar @addCart="addToCart" />
    <!-- <toast :message="message" :show="show" /> -->
  </div>
</template>

<script>
import {
  getDetail,
  getRecommend,
  Goods,
  Shop,
  GoodsParam,
} from "network/detail";

import DetailNavBar from "./childComps/DetailNavBar.vue";
import DetailSwiper from "./childComps/DetailSwiper.vue";
import DetailBaseInfo from "./childComps/DetailBaseInfo.vue";
import DetailShopInfo from "./childComps/DetailShopInfo.vue";
import DetailGoodsInfo from "./childComps/DetailGoodsInfo.vue";
import DetailParamInfo from "./childComps/DetailParamInfo.vue";
import DetailCommentInfo from "./childComps/DetailCommentInfo.vue";
import DetailBottomBar from "./childComps/DetailBottomBar.vue";

import Scroll from "components/common/scroll/Scroll.vue";
import GoodsList from "components/content/goods/GoodsList.vue";

import { debounce } from "common/utils";
import { itemListenerMixin, backTopMixin } from "common/mixin";
import { mapActions } from "vuex";

export default {
  name: "Detail",
  components: {
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    Scroll,
    DetailGoodsInfo,
    DetailParamInfo,
    GoodsList,
    DetailCommentInfo,
    DetailBottomBar,
  },
  mixins: [itemListenerMixin, backTopMixin],
  data() {
    return {
      iid: null,
      topImages: [],
      goods: {},
      shop: {},
      detailInfo: {},
      goodsParam: {},
      commentInfo: {},
      recommends: [],
      themeTopYs: [],
      getThemeTopY: null,
      currentIndex: 0,
      // message: "",
      // show: false,
    };
  },
  created() {
    //1、保存传入的iid
    this.iid = this.$route.params.iid;
    //2、根据iid请求详情数据
    getDetail(this.iid).then((res) => {
      //获取数据
      const data = res.result;
      console.log(data);

      //1、获取顶部图片轮播数据
      this.topImages = data.itemInfo.topImages;
      //2、 获取商品信息
      this.goods = new Goods(
        data.itemInfo,
        data.columns,
        data.shopInfo.services
      );
      //3、 获取店铺信息的对象
      this.shop = new Shop(data.shopInfo);
      //4、保存商品的详情数据
      this.detailInfo = data.detailInfo;
      //5、保存商品参数信息
      this.goodsParam = new GoodsParam(
        data.itemParams.info,
        data.itemParams.rule
      );
      //6、获取评论信息
      if (data.rate.cRate !== 0) {
        this.commentInfo = data.rate.list[0];
      }

      /*
      //1.第一次获取,值不对.
      //值不对的原因:this.$refs.params.$el压根没有渲染
      this.themeTopYs.push(0);
      this.themeTopYs.push(this.$refs.param.$el.offsetTop);
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      console.log(this.themeTopYs);

      //赋值完数据，等一会才更新DOM
      //下一帧 （数据渲染完 再调用）
      this.$nextTick(() => {
        //第二次值不对，图片没有加载完
        //根据最新的数据，对应的DOM是已经被渲染出来
        //但是图片依然是没有加载完(目前获取到offsetTop不包含其中的图片).
        // offsetTop值不对的时候，都是因为图片的问题

        this.themeTopYs.push(0);
        this.themeTopYs.push(this.$refs.param.$el.offsetTop);
        this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
        this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
        console.log(this.themeTopYs);
      });
      */
    });
    //3、请求推荐数据
    getRecommend().then((res) => {
      this.recommends = res.data.list;
    });
    //4.给getThemeTopY赋值(对给this.themeTopYs赋值的操作进行防抖)
    this.getThemeTopY = debounce(() => {
      this.themeTopYs = [];
      this.themeTopYs.push(0);
      this.themeTopYs.push(this.$refs.param.$el.offsetTop);
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      this.themeTopYs.push(Number.MAX_VALUE);
      console.log(this.themeTopYs);
    }, 300);
  },
  mounted() {
    // const refresh = debounce(this.$refs.scroll.refresh, 10);
    // this.itemImgListener = () => {
    //   refresh();
    //   // this.$refs.scroll.refresh();
    // };
    // this.$bus.$on("itemImageLoad", this.itemImgListener);
  },
  // updated() {
  //   this.themeTopYs = [];
  //   this.themeTopYs.push(0);
  //   this.themeTopYs.push(this.$refs.param.$el.offsetTop);
  //   this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
  //   this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
  //   console.log(this.themeTopYs);
  // },
  destroyed() {
    this.$bus.$off("itemImageLoad", this.itemImgListener);
  },
  methods: {
    ...mapActions(["addCart"]),
    addToCart() {
      //1、获取购物车需要展示的信息
      const product = {};
      product.iid = this.iid;
      product.image = this.topImages[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.price = this.goods.realPrice;
      product.count = this.goods.count;
      //2、讲商品加入购物车（1、Promise 2、mapActions）
      // this.$store.cartList.push(product)
      //要经过mutations
      // this.$store.commit("addCart", product);
      //逻辑分离 经过actions
      //通过mapActions 映射 actions.js调用addCart
      //本质和dispatch一样
      this.addCart(product).then((res) => {
        // this.show = true;
        // this.message = res;
        // setTimeout(() => {
        //   this.show = false;
        //   this.message = "";
        // }, 1500);
        this.$toast.show(res, 2000);
      });
      // this.$store.dispatch("addCart", product).then((res) => {
      //   console.log(res);
      // });
    },
    contentSrcoll(position) {
      // console.log(position);

      // 1.获取y值
      const positionY = -position.y;

      //2.positoinY和主题中值进行对比
      //[0，7938,9120，9452]
      //positoinY在0和7938之间,index =0
      // positoinY在=7938 和9120之间，index =1
      // positoinY在9120和9452之间，index = 2
      // positoinY在9120和 非常大的值之间，index = 3

      // positoinY大于等于9120值，index = 3
      const length = this.themeTopYs.length;
      //不需要取到最后一个值 max_int
      for (let index = 0; index < length - 1; index++) {
        //方法2、在数组中 再加一个很大的值 不会出现数组下标越界
        if (
          this.currentIndex !== index &&
          positionY >= this.themeTopYs[index] &&
          positionY < this.themeTopYs[index + 1]
        ) {
          this.currentIndex = index;
          console.log(this.currentIndex);
          this.$refs.nav.currentIndex = this.currentIndex;
        }

        //方法1 判断太繁琐
        // if (
        //   this.currentIndex !== index &&
        //   ((index < length - 1 &&
        //     positionY >= this.themeTopYs[index] &&
        //     positionY < this.themeTopYs[index + 1]) ||
        //     (index == length - 1 && positionY >= this.themeTopYs[index]))
        // ) {
        //   this.currentIndex = index;
        //   console.log(this.currentIndex);
        //   this.$refs.nav.currentIndex = this.currentIndex;
        // }
        //3、判断BackTop是否显示
        this.isShowBackTop = positionY > 1000;
      }
    },
    imageLoad() {
      this.newRefresh();
      // this.$refs.scroll.refresh();
      this.getThemeTopY();
    },
    titleClick(index) {
      this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 100);
    },
  },
};
</script>

<style scoped>
#tab-bar {
  display: none;
}
#detail {
  position: relative;
  z-index: 9;
  background-color: #fff;
  height: 100vh;
}

.detail-nav {
  position: relative;
  z-index: 9;
  background-color: #fff;
}

.content {
  overflow: hidden;
  position: absolute;
  background-color: #fff;
  top: 44px;
  bottom: 58px;
  left: 0;
  right: 0;
}
</style>